<template>
  <div class="job-detail-container">
    <div v-if="loading" class="loading">
      加载中...
    </div>
    
    <div v-else-if="job" class="job-detail">
      <div class="job-header">
        <h2>{{ job.title }}</h2>
        <button
                  v-if="!isRecruiterComputed && !hasApplied"
                  @click="applyForJob"
                  class="apply-btn"
                >
                  申请职位
                </button>
                <div v-else-if="hasApplied" class="applied-status">
                  您已申请此职位
                </div>
      </div>
      
      <div class="job-info">
        <div class="info-item">
          <strong>公司:</strong> {{ job.company }}
        </div>
        <div class="info-item">
          <strong>地点:</strong> {{ job.location }}
        </div>
        <div class="info-item">
          <strong>薪资:</strong> {{ job.salary || '面议' }}
        </div>
        <div class="info-item">
          <strong>发布时间:</strong> {{ formatDate(job.createdAt) }}
        </div>
      </div>
      
      <div class="job-description">
        <h3>职位描述</h3>
        <p>{{ job.description }}</p>
      </div>
      
      <div v-if="isRecruiterComputed" class="applications-section">
        <h3>申请列表 ({{ applicationStats.total }})</h3>
        <div v-if="applications.length === 0" class="no-applications">
          暂无申请
        </div>
        <div v-else class="applications-list">
          <div 
            v-for="application in applications" 
            :key="application.id" 
            class="application-card"
          >
            <div class="application-header">
              <span class="application-status" :class="application.status">
                {{ getStatusText(application.status) }}
              </span>
              <span class="application-date">
                {{ formatDate(application.createdAt) }}
              </span>
            </div>
            <div class="application-content">
                          <p><strong>申请人:</strong> {{ getApplicantUsername(application.applicantId) }}</p>
                          <p><strong>简历:</strong></p>
                          <p>{{ application.resume }}</p>
                        </div>
            <div v-if="application.status === 'pending'" class="application-actions">
              <button 
                @click="updateApplicationStatus(application.id, 'accepted')" 
                class="accept-btn"
              >
                接受
              </button>
              <button 
                @click="updateApplicationStatus(application.id, 'rejected')" 
                class="reject-btn"
              >
                拒绝
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else class="not-found">
      <p>职位不存在</p>
      <router-link to="/jobs" class="back-link">返回职位列表</router-link>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getJobById } from '../services/jobService';
import {
  submitApplication,
  getApplicationsByJob,
  updateApplicationStatus as updateAppStatus
} from '../services/applicationService';
import { getCurrentUser, isRecruiter } from '../services/authService';
import { findUserByUsername, findAllUsers } from '../services/storageService';

const route = useRoute();
const router = useRouter();

// 数据
const job = ref(null);
const loading = ref(true);
const applications = ref([]);
const applicationStats = ref({
  total: 0,
  pending: 0,
  accepted: 0,
  rejected: 0
});

// 计算属性
const isRecruiterComputed = computed(() => isRecruiter());
const hasApplied = computed(() => {
  if (!getCurrentUser()) return false;
  const userId = getCurrentUser().id;
  return applications.value.some(app => app.applicantId === userId);
});

// 加载职位数据
const loadJob = () => {
  try {
    const jobId = route.params.id;
    job.value = getJobById(jobId);
    
    if (job.value) {
      // 如果是招聘方查看自己发布的职位，或者应聘方查看职位，都需要加载申请数据
      if ((isRecruiter() && job.value.recruiterId === getCurrentUser().id) || !isRecruiter()) {
        loadApplications();
      }
    }
  } catch (err) {
    console.error('加载职位失败:', err);
  } finally {
    loading.value = false;
  }
};

// 加载申请数据
const loadApplications = () => {
  try {
    const jobId = route.params.id;
    applications.value = getApplicationsByJob(jobId);
    
    // 计算申请统计
    applicationStats.value = {
      total: applications.value.length,
      pending: applications.value.filter(app => app.status === 'pending').length,
      accepted: applications.value.filter(app => app.status === 'accepted').length,
      rejected: applications.value.filter(app => app.status === 'rejected').length
    };
  } catch (err) {
    console.error('加载申请数据失败:', err);
  }
};

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'accepted': '已接受',
    'rejected': '已拒绝'
  };
  return statusMap[status] || status;
};

// 获取申请人用户名
const getApplicantUsername = (applicantId) => {
  try {
    // 获取所有用户
    const users = findAllUsers();
    // 查找申请人
    const applicant = users.find(user => user.id === applicantId);
    return applicant ? applicant.username : '未知用户';
  } catch (err) {
    console.error('获取申请人信息失败:', err);
    return '未知用户';
  }
};

// 申请职位
const applyForJob = () => {
  router.push(`/jobs/${job.value.id}/apply`);
};

// 更新申请状态
const updateApplicationStatus = (applicationId, status) => {
  try {
    updateAppStatus(applicationId, status);
    // 重新加载申请数据
    loadApplications();
  } catch (err) {
    alert('更新申请状态失败: ' + err.message);
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadJob();
});
</script>

<style scoped>
.job-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading {
  text-align: center;
  padding: 2rem;
  font-size: 1.2rem;
  color: #7f8c8d;
}

.job-detail {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 2rem;
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #eee;
}

.job-header h2 {
  margin: 0;
  color: #2c3e50;
}

.apply-btn {
  padding: 0.75rem 1.5rem;
  background-color: #2ecc71;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.apply-btn:hover {
  background-color: #27ae60;
}

.applied-status {
  padding: 0.75rem 1.5rem;
  background-color: #f1c40f;
  color: #333;
  border-radius: 4px;
  font-weight: 500;
}

.job-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1rem;
  margin-bottom: 2rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.info-item {
  margin: 0;
  color: #34495e;
}

.job-description h3 {
  margin-top: 0;
  color: #2c3e50;
}

.job-description p {
  line-height: 1.6;
  color: #34495e;
  white-space: pre-wrap;
}

.applications-section {
  margin-top: 2rem;
  padding-top: 2rem;
  border-top: 1px solid #eee;
}

.applications-section h3 {
  margin-top: 0;
  color: #2c3e50;
}

.no-applications {
  text-align: center;
  padding: 2rem;
  color: #7f8c8d;
}

.applications-list {
  display: grid;
  gap: 1rem;
}

.application-card {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 1rem;
}

.application-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.application-status {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.application-status.pending {
  background-color: #f1c40f;
  color: #333;
}

.application-status.accepted {
  background-color: #2ecc71;
  color: white;
}

.application-status.rejected {
  background-color: #e74c3c;
  color: white;
}

.application-date {
  color: #7f8c8d;
  font-size: 0.9rem;
}

.application-content p {
  margin: 0 0 0.5rem 0;
  color: #34495e;
  line-height: 1.5;
}

.application-actions {
  display: flex;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.accept-btn,
.reject-btn {
  padding: 0.25rem 0.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.3s;
}

.accept-btn {
  background-color: #2ecc71;
  color: white;
}

.accept-btn:hover {
  background-color: #27ae60;
}

.reject-btn {
  background-color: #e74c3c;
  color: white;
}

.reject-btn:hover {
  background-color: #c0392b;
}

.not-found {
  text-align: center;
  padding: 2rem;
}

.not-found p {
  font-size: 1.2rem;
  color: #7f8c8d;
  margin-bottom: 1rem;
}

.back-link {
  color: #3498db;
  text-decoration: none;
  font-weight: 500;
}

.back-link:hover {
  text-decoration: underline;
}
</style>